﻿using System;
using System.Configuration;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using m.Channelvn.Cached.Common;
using System.Xml;

using System.Web.Caching;
using System.Collections.Generic;
using System.Data;

namespace m.Channelvn.Cached.UrlRewrite
{
    public class RewriteModule : IHttpHandlerFactory, IRequiresSessionState
    {
        public const String WurflManagerCacheKey = "__WurflManager";
        public const String WurflDataFilePath = "~/App_Data/wurfl.zip";
        public const String WurflPatchFilePath = "~/App_Data/web_browsers_patch.xml";

        public IHttpHandler GetHandler(HttpContext context, string requestType, string url1, string pathTranslated)
        {
            //Redirect to web site
            //m.Channelvn.Cached.Common.Common.RedirectWeb();

            //string useragent = (context.Request.ServerVariables["HTTP_USER_AGENT"] ?? "");
            //IWURFLManager wurflManager = HttpContext.Current.Cache[WurflManagerCacheKey] as IWURFLManager;
            //if (wurflManager == null)
            //{
            //    string wurflDataFile = HttpContext.Current.Server.MapPath(WurflDataFilePath);
            //    string wurflPatchFile = HttpContext.Current.Server.MapPath(WurflPatchFilePath);

            //    IWURFLConfigurer configurer = new InMemoryConfigurer().MainFile(wurflDataFile).PatchFile(wurflPatchFile);
            //    Object manager = WURFLManagerBuilder.Build(configurer);
            //    CacheDependency fileDependency = new CacheDependency(wurflDataFile);
            //    HttpContext.Current.Cache.Add(WurflManagerCacheKey, manager, fileDependency, DateTime.Now.AddDays(30), TimeSpan.Zero, CacheItemPriority.Normal, null);
            //}
            //string pointing_method = string.Empty;
            //string model_name = string.Empty;

            //if (wurflManager != null)
            //{
            //    IDictionary<string, string> diction = wurflManager.GetDeviceForRequest(useragent).GetCapabilities();
            //    pointing_method = diction["pointing_method"];
            //    model_name = diction["model_name"];
            //}



            if (HttpContext.Current.Request.Url.Query != String.Empty)
            {
                if (context.Request.Url.Query.Length > 0)
                {
                    context.Items["VirtualUrl"] = context.Request.Path + context.Request.Url.Query;
                }
            }
            if (context.Items["VirtualUrl"] == null)
            {
                context.Items["VirtualUrl"] = context.Request.Path;
            }


            string url = context.Request.Url.AbsolutePath;
            string rewrite = "";
            string str404 = string.Empty;
            _301Redirection _301 = new _301Redirection();
            if (!_301.Redirect(url + (context.Request.Url.Query.Length > 0 ? "?" + HttpContext.Current.Request.Url.Query.Replace("?", "") : "")))
            {
            
                RewriteRules rewriteRules;

                bool isNormalPhone;
                //if (m.Channelvn.Cached.Common.Common.IsSmartPhone())
                //{
                    //dt smat phone
                    rewriteRules = RewriteRules.GetCurrentRewriteRulesIphone();
                    str404 = "/Touch/404.aspx";
                //}
                //else
                //{
                //    isNormalPhone = Lib.isNormalPhone();
                //    if (isNormalPhone)
                //    {
                //        //dt thong thuogn
                //        rewriteRules = RewriteRules.GetCurrentRewriteRules();
                //        str404 = "/404.aspx";
                //    }
                //    else
                //    {   //dt lom nhat
                //        //rewriteRules = RewriteRules.GetCurrentRewriteRules();
                //        //str404 = "/404.aspx";
                //        rewriteRules = RewriteRules.GetCurrentRewriteRules_FP();
                //        str404 = "/Pages_FP/404.aspx";
                //    }

                //}

                rewrite = rewriteRules.GetMatchingRewrite(url);

                string currentUrl = context.Request.Url.AbsolutePath;
                string[] newRewriteUrl = null;
                string strCheck = string.Empty;
                if (rewrite.Contains("?"))
                {
                    newRewriteUrl = rewrite.Split('?');

                    if (!string.IsNullOrEmpty(strCheck))
                    {
                        _301Redirection.RedirectTo(strCheck);
                        return null;
                    }
                }

                if (!string.IsNullOrEmpty(rewrite))
                {
                    context.RewritePath("~" + rewrite);
                }
                else
                {
                    rewrite = context.Request.Path + context.Request.Url.Query;
                }
            }
            string newFilePath = rewrite.IndexOf("?") > 0 ? rewrite.Substring(0, rewrite.IndexOf("?")) : rewrite;

            if (CacheController.IsAllowDistributedCached && context.Request.Form.Count == 0)
            {
                // Check cache
                CacheSettings config = CacheSettings.GetCurrentSettings();
                CacheSettings.PageSetting pageConfig = config.GetPageSetting(rewrite);

                string dateSearch = Lib.QueryString.ViewByDate;
                string key =
                    string.Format(Constants.CACHE_NAME_FORMAT_HTML_PAGE_CONTENT,
                                  (Lib.QueryString.CategoryID == 0
                                       ? Lib.Object2Integer(pageConfig.Category)
                                       : Lib.QueryString.CategoryID), Lib.QueryString.NewsID, Lib.QueryString.ThreadID,
                                  Lib.QueryString.PageIndex, dateSearch);
                if (Common.Common.IsSmartPhone())
                {
                    key = key + "_smartphone";
                }
                else
                {
                    if (!Lib.isNormalPhone())
                    {
                        key = key + "_featurephone";
                    }
                }

                string cacheContent = "";
                if (config.EnableCache && pageConfig.EnableCache)
                {
                    if (!string.IsNullOrEmpty(pageConfig.Category))
                    {
                        cacheContent = CacheController.Get<string>(pageConfig.Category, key);
                    }
                    else
                    {
                        cacheContent = CacheController.Get<string>(key);
                    }
                }
                if (!string.IsNullOrEmpty(cacheContent))
                {
                    //context.Response.Clear();
                    context.Response.Write(cacheContent);
                    //context.Response.End();
                    newFilePath = "/blank.aspx";
                }
            }

            if (string.IsNullOrEmpty(newFilePath))
                newFilePath = "/blank.aspx";

            try
            {
                return PageParser.GetCompiledPageInstance(newFilePath, context.Server.MapPath(newFilePath), context);
            }
            catch (Exception ex)
            {
                return PageParser.GetCompiledPageInstance(str404, context.Server.MapPath(str404), context);
            }
        }

        public void ReleaseHandler(IHttpHandler handler)
        {
        }
    }
}
